/**
 * 
 */

var patient = {};
var groupVersion = '';
$(function(){
	$('section#step1').show();
	
	//加载首页数据上传控件
	$('#medicalRecord_upload').uploadify({
	        'swf'      : contextPath + '/lib/uploadify/uploadify.swf',
	        'uploader' : contextPath + '/fileUpload/drgsGroup.dhc',
	        'height': 34,
	        'width' :150,
	        'auto'  : false,//是否自动开始
	        'uploadLimit' : 1, //一次同步上传的文件数目     
	        'fileSizeLimit' : '20MB', //单个文件大小，0为无限制，可接受KB,MB,GB等单位的字符串值     
	        'queueSizeLimit' : 1, //队列中同时存在的文件个数限制
	        'fileObjName':'file',
	        'removeCompleted': true,  //是否完成后移除序列，默认为true
	        'removeTimeout' : '5',  //上传完成后队列多长时间后消失。默认 3秒    需要：removeCompleted : true,时使用
	        'progressData' :'percentage',//设置上传进度显示方式，percentage显示上传百分比，speed显示上传速度
	        'buttonText' : '<i class="fa fa-folder-open fa-lg"></i>&nbsp;&nbsp;选择首页数据',
	        'buttonClass': 'btn btn-success btn-lg',
	        'fileTypeDesc' : '支持格式:xls/xlsx.', //可选文件的描述。这个值出现在文件浏览窗口中的文件类型下拉选项中。（chrome下不支持，会显示为'自定义文件',ie and firefox下可显示描述）
	        'fileTypeExts' : '*.xls; *.xlsx; *.xml',//允许上传的文件格式
	        'multi'    : false,//是否支持多文件上传
	        'method'   :'post',//提交方式
	        'formData' : {'groupVersion':groupVersion},  
	        'debug':false,
	        'overrideEvents' : [ 'onDialogClose','onCancel', 'onUploadSuccess', 'onUploadError', 'onSelectError' ,'onUploadStart','onQueueComplete'],//重写Uploadify事件
	        //当点击文件队列中文件的关闭按钮或点击取消上传时触发
	        'onCancel': uploadify_onCancel,
	      	//返回一个错误，选择文件的时候触发  
	        'onSelectError': uploadify_onSelectError, 
	      	//检测FLASH失败调用  
	        'onFallback':function(){  
	            drgUI.warning("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。") ;
	        }, 
	        'onUploadStart' : function(){
	        	$("#medicalRecord_upload").uploadify("settings", "formData", {'groupVersion':groupVersion});  
	        	getMedicalRecordProgress(true);
	        },
	        'onUploadError' : uploadify_onUploadError,
	        'onQueueComplete':function(queueData){
	            drgUI.success('成功上传的文件数: ' + queueData.successful + ' \n 上传出错的文件数: ' + queueData.errors) ;
	        },
	        'onUploadSuccess':function(file,data,response){
                     loadGroupResultTable(data.data);
            }
	    });
	$('div#medicalRecord_upload').css('width','');
	$('#medicalRecord_upload-button').css({'height':'','line-height':'','width':'150px'});
	
	$('#diags .fa-arrow-circle-up,#opers .fa-arrow-circle-up').live('click',function(){
		if($(this).parent().prev()){
			$(this).parent().prev().before($(this).parent());
		}
	});
	$('#diags .fa-arrow-circle-down,#opers .fa-arrow-circle-down').live('click',function(){
		if($(this).parent().next()){
			$(this).parent().next().after($(this).parent());
		}
	});
	$('#diags .fa-minus-square,#opers .fa-minus-square').live('click',function(){
		$(this).parent().remove();
	});
});

function buildPatient(){
	patient = {};
	var diags = [];
	var opers = [];
	$('#step2manually table .form-control[id]').each(function(i,n){
		if(n.value!=''){
			patient[n.id] = n.value;
		}
	});
	patient['GENDER'] = $('div.checked input.gender').val();//性别
	
	//诊断
	$('#step2manually table #diags>div').each(function(){
		if ($(this).find('.code').val()!='' && $(this).find('.name').val()!='') {
			diags.push({'code':$(this).find('.code').val(),'name':$(this).find('.name').val()});
			patient['diags'] = diags;
		}
	});
	//手术
	$('#step2manually table #opers>div').each(function(){
		if ($(this).find('.code').val()!='' && $(this).find('.name').val()!='') {
			opers.push({'code':$(this).find('.code').val(),'name':$(this).find('.name').val()});
			patient['opers'] = opers;
		}
		
	});
	
	//patientList.push(patient);
}

//获取首页数据导入进度并显示
function getMedicalRecordProgress(isExcel){
	timerStart();
	if(typeof(EventSource)!=='undefined'){
		var message='';
		var source=new EventSource(contextPath +'/GroupFunc/getProgress.dhc');
		source.onmessage=function(event){
			var info=JSON.parse(event.data);
			if(message!=info.msg){
				message=info.msg;
				$('#progress_info').append('<p>'+message+'</p>');
			}
			$('#progress_info_detail').html('<p>'+info.detail+'</p>');
			$('#progress_time').html(info.time);
			$('.progress-bar').css('width',info.percent+'%');
			$('.progress-bar span').html(info.percent+'%');
			if (info.msg=='已完成') {
				clearInterval(timerId);
				source.close();
				$('#progress_info').append('<p style="color:#5FBF18;"><i class="fa fa-smile-o fa-2x"></i></p>');
				$('#progress_info').append('<p></p>');
				$('#close_loading_btn').fadeIn();
				if(isExcel){
					getGroupResult();
				}
			}else if (info.msg=='已中断') {
				clearInterval(timerId);
				source.close();
				$('#progress_info').append('<p style="color:#FF4466;"><i class="fa fa-frown-o fa-2x"></i></p>');
				$('#progress_info').append('<p></p>');
				$('#close_loading_btn').fadeIn();
			}
			
		};
	}
}

function getGroupResult(){
	$.post(contextPath + '/fileUpload/getGroupResult.dhc').done(function(result){
		$('#step4 .panel').html(result.message);
		loadGroupResultTable(result.data);
	});
}

function addRow(clazz){
	var name='诊断';
	if (clazz=='opers') {
		name='手术'
	}
	$('#'+clazz).append('<div class="form-inline">'
			+'<span>'+name+'编码：</span>'
			+'<input type="input" class="form-control code">'
			+' <span>'+name+'名称：</span>'
			+'<input type="input" class="form-control name">'
			+'<i title="向上" class="fa fa-arrow-circle-up"></i>'
			+' <i title="向下" class="fa fa-arrow-circle-down"></i>'
			+' <i title="删除" class="fa fa-minus-square"></i>'
			+'</div>')
}

function toStep1(){
	$('.step.current').removeClass('current');
	$('.step.one').removeClass('lastDone').addClass('current');
	$('section[id]').slideUp();
	$('#step1').slideDown();
}
function toStep2(type){
	$('.step.one').removeClass('done').addClass('lastDone');
	$('.step.current').removeClass('current');
	$('.step.two').removeClass('lastDone').addClass('current');
	$('section[id]').slideUp();
	if(type=='manually'){
		$('#step2manually').slideDown();
	}else{
		$('#step2excel').slideDown();
	}
}
function toStep3(type){
	$('.step.one').removeClass('lastDone').addClass('done');
	$('.step.two').removeClass('done').addClass('lastDone');
	$('.step.current').removeClass('current');
	$('.step.three').removeClass('lastDone').addClass('current');
	$('section[id]').slideUp();
	$('#step3').slideDown();
	
	if (type=='patient') {
		groupVersion = $('#step2manually .groupVersion').val();
		buildPatient();
		
		$.post(contextPath + '/GroupFunc/drgsGroupPatients.dhc', {
			'patient': JSON.stringify(patient),
			'drgVersion' : groupVersion
		}).done(function(data){
			loadGroupResultTable(data.data);
		});
		
		getMedicalRecordProgress(false);
	} else if(type=='excel'){
		
		groupVersion = $('#step2excel .groupVersion').val();
		$('#medicalRecord_upload').uploadify('upload', '*');
	}
}
function toStep4(){
	$('.step.two').removeClass('lastDone').addClass('done');
	$('.step.three').removeClass('done').addClass('lastDone');
	$('.step.current').removeClass('current');
	$('.step.four').addClass('current');
	$('section[id]').slideUp();
	$('#step4').slideDown();
}

var timerId;
function timerStart(){
	var h = 0;
	var m = 0;
	var s = 0;
	timerId = setInterval(function(){
		s++;
		if (s==60) {
			s=0;
			m++;
		}
		if (m==60) {
			m=0;
			h++;
		}
		$('#progress_usedtime').html(h+':'+m+':'+s);
	}, 1000)
}

function doGroup(type){
	var isBlank=false;
	$.each($('input[required="required"]'),function(i,n){
		if($(n).val()==''){
			setTimeout(function(){
				$(n).removeClass('ue-shake');
			}, 900);
			$(n).addClass('ue-shake');
			isBlank=true;
		}
	});
	if(isBlank) return;
	if (type=='patient') {
		$('#resultPanel .panel-body').html('<i class="fa fa-cog fa-spin fa-4x fa-fw margin-bottom text-success"></i>');
		groupVersion = $('#step2manually .groupVersion').val();
		buildPatient();
		$('#step2manually button').attr('disabled','disabled');
		$.post(contextPath + '/GroupFunc/drgsGroupPatients.dhc', {
			'patient': JSON.stringify(patient),
			'drgVersion' : groupVersion
		}).done(function(data){
			$('#step2manually button').removeAttr('disabled');
			$('#resultPanel .panel-body').html('<div class="h4" id="groupResult"></div><div class="well" id="groupResultLog"></div>');
			var d = data.data[0];
			var result=[];
			if(d.DRG_CODE){
				$('#groupResult').html('DRG代码：'+d.DRG_CODE+'<br>DRG描述：'+d.DRG_DESC);
				//result.push('DRGs代码：'+d.DRG_CODE+'');
				//result.push('DRGs描述：'+d.DRG_DESC+'');
			}
			if(d.GROUP_LOG){
			    var s = '';
          	    var logs = d.GROUP_LOG;
          	    for (var i = 0; i < logs.length; i++) {
						s+=logs[i]+'\n';
				  }
				result.push('分组日志：\n'+s);
			}
			var i=0;
			var regn = /\n/;
			var regs = /\s/;
			var timer = setInterval(function(){
				var codeArray = result.join('\n').split('');
				if (regn.test(codeArray[i])) {
					var br = document.createElement('br');
					$('#groupResultLog').append(br);
				}
//				if (regs.test(codeArray[i])) {
//					$('#groupResult').append('&nbsp;');
//				}
				$('#groupResultLog').append(codeArray[i]);
				i++;
				
				if (i>codeArray.length) {
					clearInterval(timer);
				}
			}, 50);
		});
	} else if(type=='excel'){
		groupVersion = $('#step2excel .groupVersion').val();
		$('#medicalRecord_upload').uploadify('upload', '*');
	}
}

function reGroup(){
	openTab('/pages/dataMonitor/drgsGroup.jsp', '页面分组','pageGrouping');
}

function loadGroupResultTable(data){
	toStep4();
	$('#resultTableDiv').html('<table class="table" id="resultTable">'
    	+'<thead><tr><td>病案号</td><td>性别</td><td>年龄</td><td>总费用</td><td>主要诊断</td><td>DRG代码</td><td>DRG描述</td></tr></thead>'
    	+'<tbody></tbody></table>');
	var reg = new RegExp(/^\\w{1,2}QY$/);
	var columns = [
					{ "data": "CASE_ID"},
					{ "data": "GENDER"},
					{ "data": "AGE"},
					{ "data": "TOTAL_EXPENSE"},
					{ "data": "DISEASE_NAME"},
					{ "data": "DRG_CODE",
                      "render": function(obj, type, full) {
                    	  var drgsCode = full.DRG_CODE;
                    	  var logStr = '';
                    	  var logs = full.GROUP_LOG;
                    	  for (var i = 0; i < logs.length; i++) {
                    		  logStr+=logs[i]+'\n';
						  }
                    	  return '<span data-toggle="tooltip" data-placement="left" title="未入组原因：\n'+logStr+'">'+drgsCode+'</span>';
                      }
					},
					{ "data": "DRG_DESC"}
                  ]
	$('#resultTable').drgsDataTable(columns, data);
	$('.datatable_export').css('background-image','url('+contextPath+'/images/datatable_export.png)');
	$('[data-toggle="tooltip"]').tooltip();
}